package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"strconv"

	"github.com/gofiber/fiber/v2"
	"golang.org/x/crypto/bcrypt"
)

// UserHandler 用户处理器
type UserHandler struct {
	client *ent.Client
}

// NewUserHandler 创建用户处理器
func NewUserHandler(client *ent.Client) *UserHandler {
	return &UserHandler{client: client}
}

// CreateUserRequest 创建用户请求
type CreateUserRequest struct {
	Username    string `json:"username"`
	Password    string `json:"password"`
	DisplayName string `json:"display_name"`
	Avatar      string `json:"avatar"`
}

// UpdateUserRequest 更新用户请求
type UpdateUserRequest struct {
	DisplayName string `json:"display_name"`
	Avatar      string `json:"avatar"`
	Password    string `json:"password"`
}

// UserResponse 用户响应（不包含密码）
type UserResponse struct {
	ID          int64  `json:"id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	Avatar      string `json:"avatar"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

// GetUsers 获取所有用户
func (h *UserHandler) GetUsers(c *fiber.Ctx) error {
	ctx := context.Background()
	users, err := h.client.User.Query().All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取用户列表失败")
	}

	// 转换为响应格式，不包含密码
	response := make([]UserResponse, len(users))
	for i, user := range users {
		response[i] = UserResponse{
			ID:          user.ID,
			Username:    user.Username,
			DisplayName: user.DisplayName,
			Avatar:      user.Avatar,
			CreatedAt:   user.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:   user.UpdatedAt.Format("2006-01-02 15:04:05"),
		}
	}

	return models.Success(c, response)
}

// GetUser 获取单个用户
func (h *UserHandler) GetUser(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	user, err := h.client.User.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "用户不存在")
		}
		return models.InternalServerError(c, "获取用户失败")
	}

	// 转换为响应格式，不包含密码
	response := UserResponse{
		ID:          user.ID,
		Username:    user.Username,
		DisplayName: user.DisplayName,
		Avatar:      user.Avatar,
		CreatedAt:   user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return models.Success(c, response)
}

// CreateUser 创建用户
func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateUserRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Username == "" {
		return models.BadRequest(c, "用户名不能为空")
	}

	if req.Password == "" {
		return models.BadRequest(c, "密码不能为空")
	}

	if req.DisplayName == "" {
		return models.BadRequest(c, "显示名称不能为空")
	}

	// 密码加密
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		return models.InternalServerError(c, "密码加密失败")
	}

	builder := h.client.User.
		Create().
		SetUsername(req.Username).
		SetPassword(string(hashedPassword)).
		SetDisplayName(req.DisplayName)

	// Avatar 是可选的
	if req.Avatar != "" {
		builder.SetAvatar(req.Avatar)
	}

	user, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建用户失败")
	}

	// 转换为响应格式
	response := UserResponse{
		ID:          user.ID,
		Username:    user.Username,
		DisplayName: user.DisplayName,
		Avatar:      user.Avatar,
		CreatedAt:   user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return models.SuccessWithMessage(c, "创建成功", response)
}

// UpdateUser 更新用户
func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	var req UpdateUserRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.User.UpdateOneID(id)

	// 更新显示名称
	if req.DisplayName != "" {
		builder.SetDisplayName(req.DisplayName)
	}

	// 更新头像
	if req.Avatar != "" {
		builder.SetAvatar(req.Avatar)
	}

	// 更新密码
	if req.Password != "" {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
		if err != nil {
			return models.InternalServerError(c, "密码加密失败")
		}
		builder.SetPassword(string(hashedPassword))
	}

	user, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "用户不存在")
		}
		return models.InternalServerError(c, "更新用户失败")
	}

	// 转换为响应格式
	response := UserResponse{
		ID:          user.ID,
		Username:    user.Username,
		DisplayName: user.DisplayName,
		Avatar:      user.Avatar,
		CreatedAt:   user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return models.SuccessWithMessage(c, "更新成功", response)
}

// DeleteUser 删除用户
func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	err = h.client.User.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "用户不存在")
		}
		return models.InternalServerError(c, "删除用户失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}
